﻿using CommonUtility;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using WPay.Infrastructure.Unity;

namespace Utility
{
    /// <summary>
    /// 邮件发送(POP3/SMTP)
    /// </summary>
    public class Email
    {
        private static string emailAcount = ConfigManage.GetConfigByKey("emailAcount");//"xilianxinlingshou@wumis.com";//发件人地址
        private static string emailPassword = ConfigManage.GetConfigByKey("emailPassword");//"UNnr2016";//发件人邮箱授权码/密码
        private static string XLUNEmails = ConfigManage.GetConfigByKey("XLUNEmails");

        /// <summary>
        /// 2024-02-2调整发送飞书消息
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="reciver">接收人</param>
        /// <param name="content">发送内容</param>
        /// <param name="CCEmail">抄送人</param>
        /// <param name="IsBodyHtml">是否支持HTML</param>
        /// <param name="sfile">附件地址</param>
        /// <param name="displayName">附件地址</param>
        public void SendEmail(string subject, List<string> reciver, string contentmessage, List<string> CCEmail = null, bool IsBodyHtml = false, List<string> sfile = null, string displayName = "西联新零售")
        {
            try
            {

                object[] elements = { new { tag = "markdown", content = contentmessage + $"<at id=all></at>\n" } };
                object content = new
                {
                    config = new { wide_screen_mode = true },
                    header = new { title = new { tag = "plain_text", content = $"{subject}" }, template = "lark_md" },
                    elements = elements
                };
                SendFsMessage("", Newtonsoft.Json.JsonConvert.SerializeObject(content));

            }
            catch (Exception e)
            {
                LoggerHelper.Writelog("飞书消息异常", $"{subject}飞书消息异常{e.Message + e.InnerException?.Message},ip:{IPHelper.getIPAddr()},DockerId:{IPHelper.DockerId()}====================");
            }
        }

        public void SendEmail(string subject, string contentmessage)
        {
            try
            {

                object[] elements = { new { tag = "markdown", content = contentmessage + $"<at id=all></at>\n" } };
                object content = new
                {
                    config = new { wide_screen_mode = true },
                    header = new { title = new { tag = "plain_text", content = $"{subject}" }, template = "lark_md" },
                    elements = elements
                };
                SendFsMessage("", Newtonsoft.Json.JsonConvert.SerializeObject(content));

            }
            catch (Exception e)
            {
                LoggerHelper.Writelog("飞书消息异常", $"{subject}飞书消息异常{e.Message + e.InnerException?.Message},ip:{IPHelper.getIPAddr()},DockerId:{IPHelper.DockerId()}====================");
            }
        }




        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <param name="content"></param>
        /// <param name="url"></param>
        public static void SendFsMessage(string name, string content, string url = null)
        {
            try
            {

                object model = new
                {
                    msg_type = "interactive",
                    card = content
                };
                //序列化为字符串，可以使用自己项目中封装的json方法
                string strContent = JSONSerializer.Serialize(model);
                FastPost("https://open.feishu.cn/open-apis/bot/v2/hook/9c0f942d-e0df-42a5-be68-e1f536f1157e", strContent, null, "application/json");
            }
            catch (Exception e)
            {
                LoggerHelper.Writelog("飞书消息异常", $"SendFsMessage飞书消息异常{e.Message + e.InnerException?.Message},ip: {IPHelper.getIPAddr()},DockerId: {IPHelper.DockerId()}==================== ");

            }
        }





        /// <summary>
        /// 执行post请求
        /// </summary>
        /// <param name="Url">请求路径</param>
        /// <param name="postData">参数</param>
        /// <returns></returns>
        public static void FastPost(string Url, string postDataStr, Dictionary<string, string> headervalue = null, string ContentType = "application/x-www-form-urlencoded")
        {
            try
            {
                byte[] payload;
                //将URL编码后的字符串转化为字节
                payload = System.Text.Encoding.UTF8.GetBytes(postDataStr);

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
                request.Method = "POST";
                request.ContentType = ContentType;
                request.ContentLength = payload.Length;
                if (headervalue != null)
                {
                    foreach (var item in headervalue)
                    {
                        request.Headers.Add(item.Key, item.Value);
                    }
                }

                Stream myRequestStream = request.GetRequestStream();
                myRequestStream.Write(payload, 0, payload.Length);
                myRequestStream.Close();

                HttpWebResponse response = null;
                Stream myResponseStream = null;
                try
                {
                    response = (HttpWebResponse)request.GetResponse();
                    myResponseStream = response.GetResponseStream();
                }
                catch (WebException ex)
                {
                    throw ex;
                }
                StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
                string retString = myStreamReader.ReadToEnd();
                myStreamReader.Close();
                myResponseStream.Close();


            }
            catch (Exception e)
            {


            }

        }







        /// <summary>
        /// 邮件发送
        /// </summary>
        /// <param name="subject"></param>
        /// <param name="reciver"></param>
        /// <param name="content"></param>
        /// <param name="CCEmail"></param>
        /// <param name="IsBodyHtml"></param>
        /// <param name="sfile"></param>
        /// <param name="displayName"></param>
        public void SendEmailRC(string subject, List<string> reciver, string content, List<string> CCEmail = null, bool IsBodyHtml = false, List<string> sfile = null, string displayName = "西联新零售")
        {
            try
            {
                if (reciver == null || reciver.Count <= 0)
                {
                    reciver = new List<string>() { "taowei@wumis.com" };
                }
                if (ConfigManage.GetConfigByKey("IsSedEmail") == "1" || string.IsNullOrEmpty(ConfigManage.GetConfigByKey("IsSedEmail")))
                {
                    //实例化一个发送邮件类。
                    MailMessage mailMessage = new MailMessage();
                    //发件人邮箱地址，方法重载不同，可以根据需求自行选择。
                    mailMessage.From = new MailAddress(emailAcount, displayName);
                    mailMessage.IsBodyHtml = IsBodyHtml;

                    mailMessage.BodyEncoding = System.Text.Encoding.UTF8;
                    mailMessage.Priority = MailPriority.Normal;
                    //收件人邮箱地址。
                    reciver.ForEach(x =>
                    {
                        mailMessage.To.Add(new MailAddress(x));
                    });

                    if (CCEmail != null)
                    {
                        //是否抄送
                        foreach (string ccAddress in CCEmail)
                        {
                            if (!String.IsNullOrEmpty(ccAddress))
                                mailMessage.CC.Add(ccAddress);
                        }
                    }
                    else//使用配置文件
                    {
                        var CCEmails = XLUNEmails.Split(",").ToList();
                        foreach (string ccAddress in CCEmails)
                        {
                            if (!String.IsNullOrEmpty(ccAddress))
                                mailMessage.CC.Add(ccAddress);
                        }
                    }
                    //// 添加附件
                    if (sfile != null && sfile.Count >= 0)
                    {
                        sfile.ForEach(x =>
                        {
                            mailMessage.Attachments.Add(new Attachment(x));
                        });
                    }
                    //邮件标题。
                    mailMessage.Subject = subject;
                    //邮件内容。
                    mailMessage.Body = content;
                    //实例化一个SmtpClient类。
                    SmtpClient client = new SmtpClient();

                    //在这里我使用的是qq邮箱，所以是smtp.qq.com，如果你使用的是126邮箱，那么就是smtp.126.com。
                    client.Host = "smtp.feishu.cn";
                    // client.Port = 465;
                    //使用安全加密连接。
                    client.EnableSsl = true;
                    //不和请求一块发送。
                    client.UseDefaultCredentials = false;
                    //验证发件人身份(发件人的邮箱，邮箱里的生成授权码);
                    client.Credentials = new NetworkCredential(emailAcount, emailPassword);
                    //发送
                    client.Send(mailMessage);
                }
                else
                {
                    LoggerHelper.Log("本地邮件记录:" + content);
                }
                LoggerHelper.Writelog("SendEmail", $"{subject}邮件发送成功,ip:{IPHelper.getIPAddr()},DockerId:{IPHelper.DockerId()}====================");
            }
            catch (Exception e)
            {
                LoggerHelper.Writelog("SendEmail", $"{subject}邮件发送异常{e.Message + e.InnerException?.Message},ip:{IPHelper.getIPAddr()},DockerId:{IPHelper.DockerId()}====================");
            }
        }

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">邮件标题</param>
        /// <param name="reciver">接收人</param>
        /// <param name="content">发送内容</param>
        /// <param name="CCEmail">抄送人</param>
        /// <param name="IsBodyHtml">是否支持HTML</param>
        /// <param name="sfile">附件地址</param>
        public static void SendEmailError(string subject, List<string> reciver, string content, List<string> CCEmail = null, bool IsBodyHtml = false, List<string> sfile = null)
        {
            try
            {
                //实例化一个发送邮件类。
                MailMessage mailMessage = new MailMessage();
                //发件人邮箱地址，方法重载不同，可以根据需求自行选择。
                mailMessage.From = new MailAddress(emailAcount, "西联新零售");
                mailMessage.IsBodyHtml = IsBodyHtml;
                //收件人邮箱地址。
                reciver.ForEach(x =>
                {
                    mailMessage.To.Add(new MailAddress(x));
                });

                if (CCEmail != null)
                {
                    //是否抄送
                    foreach (string ccAddress in CCEmail)
                    {
                        if (!String.IsNullOrEmpty(ccAddress))
                            mailMessage.CC.Add(ccAddress);
                    }
                }
                else//使用配置文件
                {
                    var CCEmails = XLUNEmails.Split(",").ToList();
                    foreach (string ccAddress in CCEmails)
                    {
                        if (!String.IsNullOrEmpty(ccAddress))
                            mailMessage.CC.Add(ccAddress);
                    }
                }
                //// 添加附件
                if (sfile != null && sfile.Count >= 0)
                {
                    sfile.ForEach(x =>
                    {
                        mailMessage.Attachments.Add(new Attachment(x));
                    });
                }
                //邮件标题。
                mailMessage.Subject = subject;
                //邮件内容。
                mailMessage.Body = content;
                //实例化一个SmtpClient类。
                SmtpClient client = new SmtpClient();
                //在这里我使用的是qq邮箱，所以是smtp.qq.com，如果你使用的是126邮箱，那么就是smtp.126.com。
                client.Host = "smtp.exmail.qq.com";
                //使用安全加密连接。
                client.EnableSsl = true;
                //不和请求一块发送。
                client.UseDefaultCredentials = false;
                //验证发件人身份(发件人的邮箱，邮箱里的生成授权码);
                client.Credentials = new NetworkCredential(emailAcount, emailPassword);
                //发送
                client.Send(mailMessage);
            }
            catch (Exception e)
            {
                LoggerHelper.Log("邮件发送异常:" + e.Message);
            }
        }
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="toAddress">收件人地址</param>
        /// <param name="fromAddress">发件人地址</param>
        /// <param name="toName">收件人名字</param>
        /// <param name="fromName">发件人姓名</param>
        /// <param name="title">主题</param>
        /// <param name="body">正文</param>
        /// <param name="isBodyHtml">正文是否为html格式</param>

        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="subject">主题</param>
        /// <param name="reciver">收件人</param>
        /// <param name="content">收件人内容</param>
        /// <param name="CCEmail">抄送人</param>
        public static void SendEmailSingle(string subject, string reciver, string content, List<string> CCEmail = null)
        {
            try
            {
                //实例化一个发送邮件类。
                MailMessage mailMessage = new MailMessage();
                //发件人邮箱地址，方法重载不同，可以根据需求自行选择。
                mailMessage.From = new MailAddress(emailAcount);
                //收件人邮箱地址。
                mailMessage.To.Add(new MailAddress(reciver));
                if (CCEmail != null)
                {
                    //是否抄送
                    foreach (string ccAddress in CCEmail)
                    {
                        if (!String.IsNullOrEmpty(ccAddress))
                            mailMessage.CC.Add(ccAddress);
                    }
                }
                //邮件标题。
                mailMessage.Subject = subject;
                //邮件内容。
                mailMessage.Body = content;
                //实例化一个SmtpClient类。
                SmtpClient client = new SmtpClient();
                //在这里我使用的是qq邮箱，所以是smtp.qq.com，如果你使用的是126邮箱，那么就是smtp.126.com。
                client.Host = "smtp.exmail.qq.com";
                //使用安全加密连接。
                client.EnableSsl = true;
                //不和请求一块发送。
                client.UseDefaultCredentials = false;
                //验证发件人身份(发件人的邮箱，邮箱里的生成授权码);
                client.Credentials = new NetworkCredential(emailAcount, emailPassword);
                //发送
                client.Send(mailMessage);
            }
            catch (Exception e)
            {
                LoggerHelper.Log("邮件发送异常:" + e.Message);
            }
        }


    }
}
